﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using AMM.Business;
using AMM.Business.Store;
using AMM.CustomWinControls;
using AMM.Model;
using AMM.Model.PrintModels;
using AMM.Model.Store;
using AMM.UserControls;
using Microsoft.Reporting.WinForms;

namespace AMM.Forms.Store {
    public partial class FrmProcurementOrder : FrmProcurementOrderBase {

        private int _pageIndex;
        private ProcurementOrderSearchModel _searchModel;
        private ProcurementOrderProcessor _procurementOrderProcessor;
        private List<ProcurementOrderViewModel> _procurementOrderList;

        #region Override

        protected override string FunctionCode {
            get { return "AMM1403"; }
        }

        protected override BaseSearchControl SearchControl {
            get { return new ProcurementOrderSearchControl(); }
        }

        protected override void Add() {
            this.ResetForms();
            this.ShowEditForm("新增", new ProcurementOrder() { ClassStatus = ClassStatus.Added });
            base.Add();
        }

        protected override void Amend() {
            List<ProcurementOrderViewModel> selectedList = this.dgvProcurementOrderList.GetSelectedRows<ProcurementOrderViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            ProcurementOrder procurementOrder = this._procurementOrderProcessor.FetchProcurementOrderById(selectedList[0].Key);
            procurementOrder.ClassStatus = ClassStatus.Updated;
            if ((AuditStatus)procurementOrder.Status == AuditStatus.Audited) {
                this.ShowInfo("审核的订单不能被修改！");
                return;
            }
            this.ShowEditForm("修改", procurementOrder);
            base.Amend();
        }

        protected override void Save() {
            base.Save();
        }

        protected override void Delete() {
            List<ProcurementOrderViewModel> selectedList = this.dgvProcurementOrderList.GetSelectedRows<ProcurementOrderViewModel>();
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this._procurementOrderProcessor.Delete(selectedList.Select(x => x.Key).ToArray());
                this.MDIParent.SetStatusInformation("删除成功");
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                base.Delete();
            });
        }

        protected override void Audit() {
            List<ProcurementOrderViewModel> selectedList = this.dgvProcurementOrderList.GetSelectedRows<ProcurementOrderViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                string resultMsg = string.Empty;
                ProcurementOrder procurementOrder = this._procurementOrderProcessor.FetchProcurementOrderById(selectedList[0].Key);
                if (procurementOrder.Status == (int)AuditStatus.Audited) {
                    if (this.ShowQuestion("订单已经通过审核，确定将取消审核状态！") == DialogResult.No) { return; }
                    procurementOrder.Status = (int)AuditStatus.Waiting;
                    resultMsg = "取消审核成功";
                }
                else {
                    procurementOrder.Status = (int)AuditStatus.Audited;
                    resultMsg = "审核成功";
                }
                procurementOrder.AuditedBy = LoginUserName;
                this._procurementOrderProcessor.Audit(procurementOrder);
                this.MDIParent.SetStatusInformation(resultMsg);
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                base.Audit();
            });
        }

        protected override void Print() {
            List<ProcurementOrderViewModel> selectedList = this.dgvProcurementOrderList.GetSelectedRows<ProcurementOrderViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                PrintDataSoruceHelper printDataSoruceHelper = new PrintDataSoruceHelper();
                List<PrintProcurementOrder> printProcurementOrder = printDataSoruceHelper.FetchPrintProcurementOrder(selectedList[0].Key);
                List<PrintProcurementOrderDetails> printProcurementOrderDetails = printDataSoruceHelper.FetchPrintProcurementOrderDetails(selectedList[0].Key);

                this.PrintHelperIns = new PrintHelper("ProcurementOrderPrint.rdlc", this.Text);
                this.PrintHelperIns.ReportDataSources.Add(new ReportDataSource("ds", printProcurementOrder));
                this.PrintHelperIns.ReportDataSources.Add(new ReportDataSource("ds1", printProcurementOrderDetails));
                base.Print();

                ProcurementOrder procurementOrder = this._procurementOrderProcessor.FetchProcurementOrderById(selectedList[0].Key);
                procurementOrder.PrintedDate = DateTime.Now;
                procurementOrder.IsPrinted = true;
                this._procurementOrderProcessor.Update(procurementOrder);
            }, () => {
                // for hiding
                this.PrintHelperIns.Dispose();
                this.ResetForms();
            });
        }

        protected override void Search(object sender, FrmSearch.SearchArgs e) {
            this.CreateNewThread(() => {
                if (e.IsRevert) {
                    this._searchModel = new ProcurementOrderSearchModel();
                }
                else {
                    this._searchModel = (ProcurementOrderSearchModel)e.SearchModel;
                }
            }, () => {
                this.BindProcurementOrderList();
            });
        }

        #endregion

        public FrmProcurementOrder() {
            this.InitializeComponent();

            this.dgvProcurementOrderList.DataGridViewModelType = typeof(ProcurementOrderViewModel);
            this.dgvProcurementOrderDetailList.DataGridViewModelType = typeof(ProcurementOrderDetailsViewModel);
        }

        #region Private methods

        private bool frmEdit_Edit(object sender, FrmEdit.EditArgs e) {
            bool resultFlag = false;
            ProcurementOrder procurementOrder = (ProcurementOrder)e.EditModel;
            if (procurementOrder.ProcurementOrderDetails.Count == 0) {
                this.ShowError("请添加订单明细记录！");
                return false;
            }
            this.PreventCancel = true;
            this.CreateNewThread(() => {
                if (procurementOrder.ClassStatus == ClassStatus.Added) {
                    procurementOrder.CreatedBy = LoginUserName;
                    this._procurementOrderProcessor.Insert(procurementOrder);
                }
                else {
                    procurementOrder.ModifiedBy = LoginUserName;
                    this._procurementOrderProcessor.Update(procurementOrder);
                }
                resultFlag = true;
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                if (resultFlag) {
                    this.MDIParent.SetStatusInformation("保存成功");
                    this.FormEdit.Close();
                }
            });

            this.Save();
            return true;
        }

        private void ResetForms() {
            this.BindProcurementOrderList();
            this.BindProcurementOrderDetailsList(0);
        }

        private void BindProcurementOrderList() {
            this.CreateNewThread(() => {
                this._procurementOrderList = this._procurementOrderProcessor.FetchProcurementOrderViewModelList(this._searchModel, this._pageIndex);
            }, () => {
                this.dgvProcurementOrderList.DataSource = new SortableBindingList<ProcurementOrderViewModel>(this._procurementOrderList);
                this.pceList.Records = this._searchModel.Records;
                this.pceList.DataBind();
            });
        }

        private void BindProcurementOrderDetailsList(int procurementId) {
            List<ProcurementOrderDetailsViewModel> detailsList = new List<ProcurementOrderDetailsViewModel>();
            this.CreateNewThread(() => {
                if (procurementId != 0) {
                    detailsList = this._procurementOrderProcessor.FetchProcurementOrderDetailsViewModelList(procurementId);
                }
            }, () => {
                this.dgvProcurementOrderDetailList.DataSource = new SortableBindingList<ProcurementOrderDetailsViewModel>(detailsList);
            });
        }

        private void ShowEditForm(string title, ProcurementOrder procurementOrder) {
            this.CreateNewThread(() => {
                Thread.Sleep(100);
            }, () => {
                ProcurementOrderEditControl editControl = new ProcurementOrderEditControl();
                this.FormEdit = new FrmEdit();
                editControl.BaseEditModel = procurementOrder;
                editControl.ValidatorForEdit = this.FormEdit.validatorForEdit;
                this.FormEdit.Controls.Add(editControl);
                this.FormEdit.Edit += new FrmEdit.EditEventHandler(frmEdit_Edit);
                this.FormEdit.Text = string.Format("{0}{1}", title, this.Text);
                FrmEntry.LoadAndRunDialog(this.FormEdit);
            });
        }

        #endregion

        private void FrmProcurementOrder_Load(object sender, EventArgs e) {
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this._procurementOrderProcessor = new ProcurementOrderProcessor(this.pceList.PageSize);
                this._searchModel = new ProcurementOrderSearchModel();
                this._pageIndex = 1;
            }, () => {
                this.WindowState = FormWindowState.Maximized;
                this.ResetForms();
                this.PreventCancel = false;
            });
        }

        private void pceList_Paging(object sender, PaginationArgs e) {
            this._pageIndex = e.PageIndex;
            this.BindProcurementOrderList();
        }

        private void dgvProcurementOrderList_DoubleClick(object sender, EventArgs e) {
            if (this.dgvProcurementOrderList.CurrentRow != null) {
                int procurementId = (int)this.dgvProcurementOrderList.CurrentRow.Cells["Key"].Value;
                this.BindProcurementOrderDetailsList(procurementId);
            }
        }
    }
}
